package com.qinglei.recoup.system.controller;

import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.domain.User;
import com.qinglei.recoup.system.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

/**
 * @author syp
 */
@Api(tags = "登录相关控制器-石-已完成")
@Slf4j
@Validated
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登录用户名，目前是手机号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码，需要加密", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/login")
//    @Limit(key = "login", period = 60, count = 20, name = "登录接口", prefix = "limit")
    public CommonRes login(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password, HttpServletRequest request) throws Exception {
        log.info("login username: {}, password: {}", username, password);
        CommonRes loginRes = loginService.login(username, password);
        log.info("login result: {}", loginRes);
        return loginRes;
    }

    @ApiOperation(value = "用户登出")
    @PostMapping("logout")
    public CommonRes logout() throws Exception {
        try {
            User currentUser = RecoupUtil.getCurrentUser();
            String token = RecoupUtil.getCurrentToken();
            Long userId = currentUser.getId();
            loginService.logout(userId, token, currentUser.getTenantId());
            return CommonRes.ok("退出系统成功");
        } catch (Exception e) {
            String message = "退出系统失败";
            log.error(message, e);
            throw new RecoupException(message);
        }
    }

    @ApiOperation(value = "除登录页，其他页面每分钟调用一次，检查在线状态")
    @GetMapping("check")
    public CommonRes<Object> checkAlive() throws RedisConnectException {
        User currentUser = RecoupUtil.getCurrentUser();
        loginService.checkAlive(currentUser.getId());
        return CommonRes.ok();
    }
}
